<?php

class CategoryModel extends RelationModel
{
    protected $_link = array(
        'Model' => array(
            'mapping_type'   => BELONGS_TO,
            'class_name'     => 'Model',
            'foreign_key'    => 'modelid',
            'mapping_fields' => 'tablename',
            'as_fields'      => 'tablename:model',
        ),
    );

    /*
     * 表单验证
     */
    protected $_validate = array(
        array('catname', 'require', '栏目名称不能为空！', 0, 'regex', 3),
    );

    /**
     * 添加栏目
     * @param type $data 页面提交数据
     * @return boolean]
     */
    public function addCategory($post)
    {
        $post['lang'] = LANG_ID;

        if (empty($post)) {
            $this->error = '添加栏目数据不能为空！';
            return false;
        }

        $data = $this->create($post, 1);
        if ($data) {
            //添加数据
            $catid = $this->add($data);
            if ($catid) {

                $this->repair();
                saveCache('Category');

                //扩展字段处理
                if ($post['extend']) {
                    $this->extendField($catid, $post);
                }
                return $catid;
            } else {
                $this->error = '栏目添加失败！';
                return false;
            }
        } else {
            return false;
        }
    }

    public function editCategory($post)
    {
        $post['arrparentid'] = $this->getArrParentId($post['id']);

        if (empty($post['listtype'])) {
            $post['listtype'] = 0;
        }

        $data = $this->create($post);
        if (!$data) {
            $this->error = $this->getDbError();
            return false;
        }

        if (false !== $this->save($data)) {

            //应用到子栏目
            if ($post['chage_all']) {
                $data = array();
                $arrchildid = $this->getArrChildId($post['id']);
                $data['ismenu'] = $post['ismenu'];
                $data['pagesize'] = $post['pagesize'];
                $data['template_list'] = $post['template_list'];
                $data['template_show'] = $post['template_show'];
                $this->where(' id in (' . $arrchildid . ')')->data($data)->save();
            }

            $this->repair();
            saveCache('Category');
            getCategory($post['id'], '', true);
            //扩展字段处理
            if ($post['extend']) {
                $this->extendField($post['id'], $post);
            }
            return true;
        } else {
            return false;
        }
    }

    /**
     * 删除栏目，如果有子栏目，会删除对应的子目录
     * @param type $catid 可以是数组，可以是栏目id
     * @return boolean
     */
    public function deleteCatid($catid)
    {
        if (!$catid) {
            return false;
        }
        $where = array();
        //取得子栏目
        if (is_array($catid)) {
            $where['id'] = array("IN", $catid);
            $catList = $this->where($where)->select();
            foreach ($catList as $cat) {
                //是否存在子栏目
                if ($cat['child'] && $cat['type'] == 0) {
                    $arrchildid = explode(",", $cat['arrchildid']);
                    unset($arrchildid[0]);
                    $catid = array_merge($catid, $arrchildid);
                }
            }
            $where['id'] = array("IN", $catid);
        } else {
            $where['id'] = $catid;
            $catInfo = $this->where($where)->find();
            //是否存在子栏目
            if ($catInfo['child'] && $catInfo['type'] == 0) {
                $arrchildid = explode(",", $catInfo['arrchildid']);
                unset($arrchildid[0]);
                $catid = array_merge($arrchildid, array($catid));
                $where['id'] = array("IN", $catid);
            }
        }
        //检查是否存在数据，存在数据不执行删除
        if (is_array($catid)) {
            $modeid = array();
            foreach ($catid as $cid) {
                $catinfo = getCategory($cid);
                if ($catinfo['modelid'] && $catinfo['type'] == 0) {
                    $modeid[$catinfo['modelid']] = $catinfo['modelid'];
                }
            }
            foreach ($modeid as $mid) {
                $tbname = ucwords(getModel($mid, 'tablename'));
                if (!$tbname) {
                    return false;
                }
                if ($tbname && M($tbname)->where(array("catid" => array("IN", $catid)))->count()) {
                    return false;
                }
            }
        } else {
            $catinfo = getCategory($catid);
            $tbname = ucwords(getModel($catInfo['modelid'], 'tablename'));
            if (!$tbname && $catinfo['type'] == 0) {
                return false;
            }
            if ($tbname && $catinfo['type'] == 0 && M($tbname)->where(array("catid" => $catid))->count()) {
                return false;
            }
            if ($catinfo['type'] == 1) {
                M('Page')->where('catid='.$catid)->delete();
            }
        }

        $status = $this->where($where)->delete();
        //更新缓存
        saveCache('Category');
        if (false !== $status) {
            $this->extendFieldDel($where);
            return true;
        } else {
            return false;
        }
    }

    /**
     * 删除某栏目下的扩展字段
     * @param type $where 删除条件
     * @return boolean
     */
    protected function extendFieldDel($where)
    {
        if (empty($where)) {
            return false;
        }
        $data['catid'] = $where['id'];
        return M('CategoryField')->where($where)->delete() !== false ? true : false;
    }

    /**
     * 获取扩展字段
     * @param type $catid 栏目ID
     * @return boolean
     */
    public function getExtendField($catid)
    {
        if (empty($catid)) {
            return false;
        }
        $extendFieldLisr = M('CategoryField')->where(array('catid' => $catid))->select();
        foreach ($extendFieldLisr as $k => $rs) {
            $extendFieldLisr[$k]['setting'] = unserialize($rs['setting']);
        }
        return $extendFieldLisr;
    }

    /**
     * 扩展字段处理
     * @param type $catid 栏目ID
     * @param type $post 数据
     * @return boolean
     */
    public function extendField($catid, $post)
    {
        if (empty($catid) || intval($catid) < 1 || empty($post)) {
            return false;
        }
        C('TOKEN_ON', false);
        //时间
        $time = time();
        //栏目信息
        $info = $this->where(array('id' => $catid))->find();
        if (empty($info)) {
            return false;
        }
        $info['setting'] = unserialize($info['setting']);
        //删除不存在的选项
        if (!empty($post['extenddelete'])) {
            $extenddelete = explode('|', $post['extenddelete']);
            M('CategoryField')->where(array('fid' => array('IN', $extenddelete)))->delete();
        }
        //查询出该栏目扩展字段列表
        $extendFieldLisr = array();
        foreach (M('CategoryField')->where(array('catid' => $catid))->field('fieldname')->select() as $rs) {
            $extendFieldLisr[] = $rs['fieldname'];
        }
        //检查是否有新怎字段
        if (!empty($post['extend_config']) && is_array($post['extend_config'])) {
            $validate = array(
                array('catid', 'require', '栏目ID不能为空！', 1, 'regex', 3),
                array('fieldname', 'require', '键名不能为空！', 1, 'regex', 3),
                array('type', 'require', '类型不能为空！', 1, 'regex', 3),
                array('fieldname', '/^[a-z_0-9]+$/i', '键名只支持英文、数字、下划线！', 0, 'regex', 3),
            );
            foreach ($post['extend_config'] as $field => $rs) {
                //如果已经存在则跳过
                if (in_array($field, $extendFieldLisr)) {
                    continue;
                }
                $rs['catid'] = $catid;
                $data = M('CategoryField')->validate($validate)->create($rs);
                if ($data) {
                    $data['create_time'] = $time;
                    $setting = $data['setting'];
                    if ($data['type'] == 'radio' || $data['type'] == 'checkbox') {
                        $option = array();
                        $optionList = explode("\n", $setting['option']);
                        if (is_array($optionList)) {
                            foreach ($optionList as $rs) {
                                $rs = explode('|', $rs);
                                if (!empty($rs)) {
                                    $option[] = array(
                                        'title' => $rs[0],
                                        'value' => $rs[1],
                                    );
                                }
                            }
                            $setting['option'] = $option;
                        }
                    }
                    $data['setting'] = serialize($setting);
                    $fieldId = M('CategoryField')->add($data);
                    if ($fieldId) {
                        $extendFieldLisr[] = $field;
                    }
                } else {
                    continue;
                }
            }
        }
        //值更新
        $extend = array();
        if (!empty($post['extend']) || is_array($post['extend'])) {
            foreach ($post['extend'] as $field => $value) {
                if (in_array($field, $extendFieldLisr)) {
                    $extend[$field] = $value;
                }
            }
            $info['setting']['extend'] = $extend;
        }
        //更新栏目
        $status = $this->where(array('id' => $catid))->save(
            array(
                'setting' => serialize($info['setting']),
            )
        );
        //删除缓存
        getCategory($catid, '', true);
        return $status !== false ? true : false;
    }

    public function repair()
    {
        @set_time_limit(500);

        $Categorys = array();

        $categoryArr = $this->where('lang=' . LANG_ID)->Order('listorder desc,id ASC')->select();
        foreach ($categoryArr as $key => $c) {
            $Categorys[$c['id']] = $c;
        }

        if (is_array($Categorys)) {

            foreach ($Categorys as $id => $cat) {
                $data = array();
                $Categorys[$id]['arrparentid'] = $arrparentid = $this->getArrParentId($id);
                $Categorys[$id]['arrchildid'] = $arrchildid = $this->getArrChildId($id);

                $child = is_numeric($arrchildid) ? 0 : 1;

                if ($cat['type'] < 2) {
                    $url = geturl($cat, '', $this->Urlrule);
                    $data['url'] = $url[0];
                    if (empty($cat['catdir'])) {
                        $data['catdir'] = $this->getCatdir($cat['catname'], $cat['id']);
                    }
                } else {
                    $data['catdir'] = '';
                    $data['url'] = $cat['url'];
                }

                $data['arrparentid'] = $arrparentid;
                $data['arrchildid'] = $arrchildid;
                $data['child'] = $child;
                $data['id'] = $cat['id'];
                $this->save($data);
            }
        }
    }

    public function getArrParentId($id, $arrparentid = '')
    {
        $Categorys = getCache('Category_' . LANG_NAME);
        if (!is_array($Categorys) || !isset($Categorys[$id])) {
            return false;
        }

        $parentid = $Categorys[$id]['parentid'];
        $arrparentid = $arrparentid ? $parentid . ',' . $arrparentid : $parentid;

        if ($parentid) {
            $arrparentid = $this->getArrParentId($parentid, $arrparentid);
        } else {
            $Categorys[$id]['arrparentid'] = $arrparentid;
        }
        return $arrparentid;
    }

    public function getArrChildId($id)
    {
        $arrChildId = $id;
        $Categorys = getCache('Category_' . LANG_NAME);
        if (is_array($Categorys)) {

            foreach ($Categorys as $catid => $cat) {

                if ($cat['parentid'] && $id != $catid) {

                    $arrparentids = explode(',', $cat['arrparentid']);

                    if (in_array($id, $arrparentids))
                        $arrChildId .= ',' . $catid;
                }
            }
        }
        return $arrChildId;
    }

    // 获取栏目letter名称
    function getCatdir($catname, $catid = "")
    {
        $catdir = Pinyin(strtolower($catname));

        $r = $this->where("catdir='{$catdir}'")->find();
        if (!empty($r) && $r['id'] != $catid) {
            $catdir = str_replace(" ", "", $catdir) . $catid;
        } else {
            $catdir = str_replace(" ", "", $catdir);
        }

        return $catdir;
    }
}